using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcShop.Models;
using MvcShop.Models.Repositories;
using MvcShop.MVC.Validation;
using MvcShop.Models.ViewDataModels;
using System.ComponentModel;


namespace MvcShop.MVC.Areas.Admin.Controllers
{
    public class GeneralUsersManageController : Controller
    {
        //
        // GET: /GeneralUsersManage/
        #region ==== Fields ====
        public const int pageSize = 40;
        public IUserRepository<User> _userRepository;
        public IUserInfoRepository<UserInfo> _userInfoRepository;
        private UsersViewData _usersData;
        #endregion

        #region ==== Constructors ====
        public GeneralUsersManageController(IUserRepository<User> userRepository, IUserInfoRepository<UserInfo> userInfoRepository)
        {
            this._userRepository = userRepository;
            this._userInfoRepository = userInfoRepository;
            this._usersData = UsersView.Data;
        }
        #endregion

        public ActionResult Index(int? page)
        {
            var criteria = new NotEqualCriteria("UserId", 0);

            this.UsersData.WithPageIndex((page == null) ? 1 : Convert.ToInt32(page));
            this.UsersData.WithCount(this._userRepository.Count(criteria));
            this.UsersData.WithTotal(pageSize);

            Order orderExpr = new Order(OrderType.DESC, "LastLoginTime");
            this.UsersData.WithUsers(this._userRepository.FindAll(this.UsersData.PageIndex, pageSize, orderExpr));
            return View(this.UsersData);
        }

        public ActionResult NIndex()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetUserList([DefaultValue(1)]int page, [DefaultValue(20)]int rp,
            [DefaultValue("UserId")]string sortname, [DefaultValue("desc")]string sortorder,
            [DefaultValue(null)]string query, [DefaultValue("UserName")]string qtype)
        {
            OrderType orderType = OrderType.DESC;
            if (sortorder == "asc") orderType = OrderType.ASC;

            ICriteria criteria = new NotEqualCriteria("UserId", 0);
            if (!string.IsNullOrEmpty(query))
            {
                if (qtype == "UserId")
                {
                    int temp;
                    if(Int32.TryParse(query,out temp))
                      criteria = new EqualCriteria(qtype, temp);
                }
                else
                {
                    criteria = new LikeCriteria(qtype, query);
                }
            }

            Order orderExpr = new Order(orderType, sortname);
            int pCount = this._userRepository.Count(criteria);

            var products = this._userRepository.Find(criteria, page, rp, orderExpr);
            var nl = from n in products
                     select new Rows { id = n.UserId, cell = new object[] { n.UserId, n.UserName, n.Email, n.LastLoginIP, n.LastLoginTime.ToString(), n.LastLogoutTime.ToString(), n.LoginTimes } };

            return Json(new { total = pCount, page = page, rows = nl });
        }

        [HttpPost]
        public ActionResult FindUser(string userName,string email)
        {
            ICriteria criteria = null;
            if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(email))
            {
                if (!String.IsNullOrEmpty(userName))
                    criteria = new EqualCriteria("UserName", userName);

                if (!String.IsNullOrEmpty(email))
                    criteria = new EqualCriteria("Email", email);
            }
            else
            {
                return RedirectToAction("Index");
            }

            var user = this._userRepository.Find(criteria).First();
            return View();
        }

        public ActionResult Details(int id)
        {
            var userInfo = this._userInfoRepository.Find(id);
            return View(userInfo);
        }

        public ActionResult Delete(int id)
        {
            var userInfo = this._userInfoRepository.Find(id);
            if (userInfo != null)
            {
                this._userInfoRepository.Del(userInfo);
                this._userInfoRepository.SaveChanges();
            }
            this._userRepository.Del(this._userRepository.Find(id));
            this._userRepository.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Del(string userId)
        {
            var caid = StringExtensions.ConvertIntList(userId);
            this._userInfoRepository.Del(caid);
            this._userRepository.Del(caid);

            return RedirectToAction("NIndex");
        }

        public UsersViewData UsersData { get { return this._usersData; } }
    }
}
